package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.login.GuiGuLogin;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.result.Result;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * projectName: tingshu-parent
 *
 * @author: 王宝贵
 * time: 2024/10/25 20:00 周五
 * description:
 */
@Slf4j
@Service
public class RabbitMqController {


    @Autowired
    private UserAccountService userAccountService;


    /**
     * 消费者
     * @param userId 用户id
     * @param message  消息主体
     * @param channel 封装与rabbit通信的方法
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = {MqConst.ROUTING_USER_REGISTER}
    ))
    @GuiGuLogin
    @SneakyThrows
    public void  initUserAccount(Long userId, Message message, Channel channel){
        try {
            if(userId !=null){
                //收到消息 执行业务
                userAccountService.initUserAccount(userId);
            }
        } catch (Exception e) {
            //重试--  不是批量处理 放回到队列里面
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //TODO 后期可以扩展业务 记录日志到数据库里 定期处理异常消息
        }

        //手动确认消息 不批量处理消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }



}